<template>
  <div class="main-container">
    <!-- 两列布局 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="data-show">
          <div class="data-title">
            <h3>个性化推荐标签</h3>
          </div>
          <div class="data-table data-tag-content">
            <template v-if="personTags.length > 0">
              <el-tag class="data-tag" type="primary" v-for="(item, index) in personTags" :key="index">{{ item }}</el-tag>
            </template>
            <div v-else class="recommend-empty">
              <i class="iconfont icon-wushuju1 data-empty-icon"></i>
              <h3 class="data-empty">暂无数据</h3>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="data-show">
          <div class="data-title">
            <h3>群组推荐标签</h3>
          </div>
          <div class="data-table data-tag-content">
            <template v-if="groupTags.length > 0">
              <el-tag class="data-tag" type="primary" v-for="(item, index) in groupTags" :key="index">{{ item }}</el-tag>
            </template>
            <div v-else class="recommend-empty">
              <i class="iconfont icon-wushuju1 data-empty-icon"></i>
              <h3 class="data-empty">暂无数据</h3>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <!-- 生成信息表单部分 -->
    <div class="data-show">
    <el-form ref="taskForm" :model="taskData" :rules="rules">
      <!-- 标题 -->
      <div class="data-title data-title-between">
        <h3>生成配置</h3>
        <div class="data-title-actions">
          <span class="action aniTxtBtn" @click="handleGenerate">生成载体</span>
        </div>
      </div>
      <!-- 内容区 -->
      <div class="data-table">
        <!-- 通用布局行 -->
        <div class="common-row row-between">
          <!-- 配置项 - 任务名称 -->
          <div class="common-item item-3">
            <label class="condition-label">情感</label>
            <el-form-item class="condition-input" prop="emotion">
              <!-- <el-input type="text" placeholder="请输入情感" v-model="taskData.emotion" /> -->
              <el-select v-model="taskData.emotion" clearable placeholder="请选择情感">
                <el-option v-for="(item, index) in emotions" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <!-- 配置项 - 平台 -->
          <div class="common-item item-3">
            <label class="condition-label">主题</label>
            <el-form-item class="condition-input" prop="subject">
              <el-select v-model="taskData.subject" clearable placeholder="请选择主题">
                <el-option v-for="(item, index) in subjects" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <!-- 配置项 - 媒体类型 -->
          <div class="common-item item-3">
            <label class="condition-label">媒体类型</label>
            <el-form-item class="condition-input checkbox-input" prop="option">
              <el-checkbox-group @change="optionChange" v-model="generateObj.selectGenerate">
                <el-checkbox
                  v-for="(item, index) in generateTypes"
                  :label="item.label"
                  :value="item.value"
                />
              </el-checkbox-group>
            </el-form-item>
          </div>
        </div>
        <!-- 通用布局行 -->
        <div class="common-row">
          <div class="common-item item-10">
            <label class="condition-label">关键词</label>
            <el-form-item class="condition-input" prop="keywords">
              <el-input @change="keywordsChange" v-model="generateObj.keywords" maxlength="100" type="textarea" show-word-limit :rows="4" resize="none" placeholder="请输入关键词以 , 分隔" />
            </el-form-item>
          </div>
        </div>
      </div>
    </el-form>
    </div>
    <!-- 生成的文章部分 -->
    <div class="data-show">
      <div class="data-title">
        <h3>文本预览</h3>
      </div>
      <div class="data-table media-container">
        <template v-if="generateObj.articles.length > 0">
          <div class="media-item" v-for="(item, index) in generateObj.articles" :key="index">
            <div class="media-music">
              <i class="iconfont icon-copy media-icon-mus"></i>
            </div>
            <el-tooltip content="下载">
              <i @click="download(item)" class="iconfont icon-xiazai1 media-action media-action-text"></i>
            </el-tooltip>
          </div>
        </template>
      </div>
      <!-- <div class="data-table article-table" :class="{'article-table-empty': !generateObj.articles}">
        <div v-if="generateObj.articles">
          <p class="article-content">{{ generateObj.articles }}</p>
          <div class="article-btns">
            <span class="btn" @click="copy">
              <i class="iconfont icon-fuzhi3"></i>
              复制
            </span>
          </div>
        </div>
        <div v-else class="recommend-empty article-empty">
          <i class="iconfont icon-wushuju1 data-empty-icon"></i>
          <h3 class="data-empty">暂无数据</h3>
        </div>
      </div> -->
    </div>
    <!-- 两列布局 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="data-show">
          <div class="data-title">
            <h3>图片预览</h3>
          </div>
          <div class="data-table media-container">
            <template v-if="generateObj.images.length > 0">
              <div class="media-item" v-for="(item, index) in generateObj.images" :key="index">
                <el-image
                  class="media-img"
                  :src="getStatic(item)"
                  fit="cover"
                  :preview-src-list="[getStatic(item)]"
                ></el-image>
                <el-tooltip content="下载">
                  <i class="iconfont icon-xiazai1 media-action" @click="download(item)"></i>
                </el-tooltip>
              </div>
            </template>
            <div v-else class="recommend-empty article-empty">
              <i class="iconfont icon-wushuju1 data-empty-icon"></i>
              <h3 class="data-empty">暂无数据</h3>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="data-show">
          <div class="data-title">
            <h3>音频预览</h3>
          </div>
          <div class="data-table media-container">
            <template v-if="generateObj.audios.length > 0">
              <div class="media-item" v-for="(item, index) in generateObj.audios" :key="index">
                <div class="media-music">
                  <i class="iconfont icon-a-mymusic media-icon-mus"></i>
                  <audio class="media-music-content" controls :src="getStatic(item)"></audio>
                </div>
              </div>
            </template>
            <div v-else class="recommend-empty article-empty">
              <i class="iconfont icon-wushuju1 data-empty-icon"></i>
              <h3 class="data-empty">暂无数据</h3>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script setup>
import { ref, computed, onActivated } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { API } from '@/utils/status';
import { fileDownload } from '@/api/file';
import * as request from '@/api/recommend';
import * as rule from '@/utils/rules';
import useAppStore from '@/stores/app';
// 假数据 - 生成按钮底下的类别选择描述数组
const generateTypes = [
  { value: 'text', label: '文本' },
  { value: 'pic', label: '图片' },
  { value: 'audio', label: '音频' }
];
const emotions = [
  { value: 'positive', label: '正向' },
  { value: 'negative', label: '反向' }
];
const subjects = [
  { value: 'military', label: '军事' },
  { value: 'culture', label: '文化' },
  { value: 'crime', label: '犯罪' },
  { value: 'education', label: '教育' },
  { value: 'medical', label: '医学' },
  { value: 'entertainment', label: '娱乐' },
  { value: 'leisure', label: '休闲' },
  { value: 'economy', label: '经济' },
  { value: 'disaster', label: '灾害' },
  { value: 'politics', label: '政治' },
  { value: 'religion', label: '宗教' },
  { value: 'science', label: '科学' },
  { value: 'sports', label: '体育' },
  { value: 'weather', label: '天气' }
];


// ==========> data <==========
const appStore = useAppStore();
const getStatic = computed(() => {
  return function (url){
    // return url.replace(/http:\/\/.*:\w{2,}/, API.generate.staticURL);
    return `${import.meta.env.VITE_APP_BASE_API}${url}`;
  }
});
const rules = {
  emotion: rule.createRequired('情感不能为空,请选择'),
  subject: rule.createRequired('主题不能为空,请选择'),
  option: [
    { required: true, validator: optionsValidator, trigger: 'blur' }
  ],
  keywords: [
    { required: true, validator: keywordsValidator, trigger: ['blur', 'change'] }
  ]
};
const route = useRoute();
const taskForm = ref(null);
const userId = ref(null);
const platformId = ref(null);
const personTags = ref([]);
const groupTags = ref([]);
const taskData = ref({
  keywords: [],
  option: {
    pic: false,
    text: false,
    audio: false
  },
  emotion: '',
  subject: ''
});


// 生成的文章、图片、音频对象
const generateObj = ref({
  keywords: '',
  selectGenerate: [],
  articles: '',
  images: [],
  audios: []
});
// <============

// ==========> hooks <==========
// generateObj.value.images.length = 15;
// generateObj.value.images.fill(avatar);
// generateObj.value.audios.length = 15;
// generateObj.value.audios.fill(music);
init();
onActivated(() => {
  init();
});

// ==========> methods <==========
// 媒体类型验证
function optionsValidator(rule, value, callback){
  let keys = Object.keys(value);
  let result = keys.some(key => {
    return taskData.value.option[key] === true;
  });
  if (!result){
    callback(new Error('请至少选择一种媒体类型!'));
  } else {
    callback();
  }
}
// 关键词验证
function keywordsValidator(rule, value, callback){
  if (value.length < 1){
    callback(new Error('关键词不能为空，请输入'));
  } else {
    let result = value.some(key => key === '');
    if (result){
      callback(new Error('关键词中含有为空项，请核对'));
    } else {
      callback();
    }
  }
}
function init(){
  if (userId.value !== 0 && userId.value !== '0' && !userId.value){
    userId.value = route && route.query && route.query.userId ? route.query.userId : null;
  }
  if (platformId.value !== 0 && platformId.value !== '0' && !platformId.value){
    platformId.value = route && route.query && route.query.platformId ? route && route.query && route.query.platformId : null;
  }
  getUserTag();
  getGroupTag();
}
// 获取个性化推荐标签
function getUserTag(){
  request.geTagByUser({
    userId: userId.value,
    platformId: platformId.value
  })
    .then(res => {
      // let result;
      // if (res){
      //   result = JSON.parse(res);
      //   if (result && result.code === 200 && result.data) {
      //     personTags.value = result.data;
      //   } else {
      //     let msg = result.msg || result.message || '获取个性化推荐标签失败';
      //     ElMessage.error(msg);
      //   }
      // }
      let result = JSON.parse(res);
      if (result && result.code === 200 && result.data && result.data.tags && Array.isArray(result.data.tags)){
        personTags.value = result.data.tags;
      } else {
        let msg = result.msg || result.message || '获取个性化标签失败，请稍后重试或联系管理员';
        ElMessage.error(msg);
      }
    })
}
// 获取群组推荐标签
function getGroupTag(){
  request.getTagByGroup({
    userId: userId.value,
    platformId: platformId.value,
    page: 1
  })
    .then(res => {
      let result = JSON.parse(res);
      if (result && result.code === 200 && result.data && result.data.tags && Array.isArray(result.data.tags)){
        groupTags.value = result.data.tags;
      } else {
        let msg = result.msg || result.message || '生成群组标签失败，请稍后重试或联系管理员';
        ElMessage.error(msg);
      }
    })
}
// 选择生成载体媒体类型事件
function optionChange(e){
  taskData.value.option.audio = false;
  taskData.value.option.text = false;
  taskData.value.option.pic = false;
  if (Array.isArray(e) && e.length > 0){
    e.forEach(key => {
      taskData.value.option[key] = true;
    });
  } 
}
// 输入关键词
function keywordsChange(e){
  if (e){
    taskData.value.keywords = e.split(',');
  }
}
function handleGenerate(){
  taskForm.value.validate((valid) => {
    if (valid){
      appStore.openLoading('载体生成中...');
      request.generateCarrier(taskData.value)
        .then(res => {
          let result;
          appStore.closeLoading();
          if (res){
            result = JSON.parse(res);
            if (result && result.code === 200 && result.data){
              ElMessage.success('生成载体成功');
              generateObj.value.articles = [result.data.text];
              generateObj.value.images = result.data.pics;
              generateObj.value.audios = result.data.audios;
            } else {
              ElMessage.error('生成载体失败，请稍后重试或联系管理员');
            }
          }
        })
        .catch(err => {
          console.log(err);
          appStore.closeLoading();
        })
    } else {
      ElMessage.warning('输入配置有误，请核对')
    }
  })
}
function download(item){
  ElMessage.success('下载开始！');
  let xhr = new XMLHttpRequest();
  xhr.open('get', `${import.meta.env.VITE_APP_BASE_API}${item}`, true);
  xhr.send();
  xhr.responseType = 'blob';
  xhr.onload = function (){
    if (this.status >= 200 && this.status < 300 || this.status == 304){
      let blob = new Blob([this.response]),
          a = document.createElement('a'),
          fileUrl = window.URL.createObjectURL(blob),
          filename = this.responseURL.slice(this.responseURL.lastIndexOf('/') + 1);
          a.href = fileUrl;
      a.download = filename;
      a.click();
      window.URL.revokeObjectURL(fileUrl);
    } else {
      ElMessage.error('下载失败，请稍后重试或联系管理员');
    }
  }
}


</script>
<style lang='scss' scoped>
@import '@/assets/styles/mixin.scss';
.prompt-container {
  height: 100px;
  overflow-y: auto;
  line-height: 2;
  word-break: keep-all;
  @include scrollBar;
}
.interval {
  margin: 0 10px;
}
.btn-condition {
  height: 150px;
  padding-top: 5px;
  .button {
    margin: 0 auto;
  }
}
.generate-checkbox {
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 100%;
  .el-checkbox {
    width: 100%;
    margin: 5px 0 0 0;
  }
  .el-checkbox::v-deep .el-checkbox__inner {
    display: none;
  }
  .el-checkbox::v-deep .el-checkbox__label {
    display: inline-block;
    width: 100%;
    height: 26px;
    line-height: 26px;
    text-align: center;
    border-radius: 4px;
    background-color: var(--color-gray-7);
  }
  .el-checkbox.is-checked::v-deep .el-checkbox__label {
    color: var(--color-white-10);
    background-color: var(--color-main);

  }
}
.data-tag-content {
  height: 120px;
  overflow-y: auto;
  @include scrollBar;
}
.data-tag {
  margin: 10px 10px;
  cursor: pointer;
}
.article-table {
  position: relative;
  padding: 10px 10px 40px 10px;
  .article-btns {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 40px;
    padding-right: 20px;
    @include flex-end-center;
  }
}
// 图片和音频的媒体容器
.media-container {
  white-space: nowrap;
  overflow-x: auto;
  height: 140px;
  @include scrollBarHor;
  .media-item {
    display: inline-block;
    width: 100px;
    height: 100px;
    margin: 5px 10px;
    border-radius: 8px;
    overflow: hidden;
    position: relative;
  }
  .media-action {
    width: 20px;
    height: 20px;
    position: absolute;
    bottom: 4px;
    right: 4px;
    border-radius: 50%;
    border: 2px solid var(--color-main);
    background-color: var(--color-white-10);
    color: var(--color-main);
    cursor: pointer;
    font-size: 12px;
    @include flex-all-center;
  }
  .media-action-text {
    border: 2px solid var(--color-white-10);
    background-color: var(--color-main);
    color: var(--color-white-10);
  }
}
.media-img {
  @include wh-100;
}
.media-music {
  @include wh-100;
  background-color: var(--color-main-8);
  position: relative;
  @include flex-all-center;
  .media-icon-mus {
    color: var(--color-white-10);
    font-size: 30px;
  }
  .media-music-content {
    width: 110%;
    height: 20px;
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
  }
}
.row-between {
  justify-content: space-between;
}
.item-3 {
  width: 30%
}
.item-10 {
  width: 100%;
  height: auto;
  padding: 10px 0;
  .condition-label {
    width: 15%;
  }
  .condition-input {
    width: 80%;
  }
}
.item-10-spe {
  width: 100%;
  .condition-label {
    width: 15%;
  }
  .condition-input {
    width: 80%;
  }
  &::v-deep .el-form-item__content {
    align-items: center!important;
  }
}
.checkbox-input .el-checkbox-group {
  width: 100%;
  align-items: center;
  display: flex;
  flex-wrap: wrap;
  font-size: var(--font-size);
  line-height: 32px;
  min-width: 0;
  position: relative;
}
.checkbox-input .el-checkbox {
  flex: 1;
  border-radius: 4px;
  background-color: var(--color-gray-7);
  &::v-deep .el-checkbox__input {
    display: none;
  }
  &::v-deep .el-checkbox__label {
    width: 100%;
    display: inline-block;
    text-align: center;
    padding: 0;
  }
}
.checkbox-input .el-checkbox.is-checked {
  background-color: var(--color-main);
  &::v-deep .el-checkbox__label {
    color: var(--color-white-10)!important;
  }
}
.recommend-empty {
  width: 100%;
  height: 100%;
  min-height: 100px;
  background-color: var(--color-gray-5);
  @include flex-all-center;
  // 无数据提示语
  .data-empty {
    color: var(--color-main-5);
    font-size: 16px;
  }
  // 无数据图标
  .data-empty-icon {
    color: var(--color-main-5);
    font-size: 32px;
  }
}
.article-table-empty {
  padding: 10px;
}
.data-title-between {
  @include flex-between-center;
  .data-title-actions {
    display: flex;
  }
}
</style>